package com.ruoyi.client.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.bookbus.domain.BookAddress;
import com.ruoyi.bookbus.domain.BookOrder;
import com.ruoyi.bookbus.domain.BookOrderItem;
import com.ruoyi.bookbus.domain.BookProduct;
import com.ruoyi.client.mapper.OrderItemMapper;
import com.ruoyi.client.mapper.OrderMapper;
import com.ruoyi.client.pojo.form.OrderInsertForm;
import com.ruoyi.client.pojo.form.OrderItemInsertForm;
import com.ruoyi.client.pojo.form.OrderQueryPageForm;
import com.ruoyi.client.pojo.form.OrderUpdateStatusForm;
import com.ruoyi.client.pojo.vo.OrderDetailVo;
import com.ruoyi.client.pojo.vo.OrderItemVo;
import com.ruoyi.client.service.AddressService;
import com.ruoyi.client.service.GoodsService;
import com.ruoyi.client.service.OrderService;
import com.ruoyi.common.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("ClientOrderServiceImpl")
public class OrderServiceImpl implements OrderService {

    @Resource(name = "ClientOrderMapper")
    private OrderMapper orderMapper;
    
    @Resource(name = "ClientOrderItemMapper")
    private OrderItemMapper orderItemMapper;

    @Resource
    private AddressService addressService;

    @Resource
    private GoodsService goodsService;

    /**
     * 增加订单（从商品列表创建）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(OrderInsertForm form) {
        if (!StpUtil.isLogin()) {
            throw new ServiceException("用户未登录");
        }
        Long userId = StpUtil.getLoginIdAsLong();

        //检查地址，确保存在并是自己的地址
        Long addressId = form.getAddressId();
        BookAddress address = addressService.selectByPrimaryKey(addressId);
        if (address == null) {
            throw new ServiceException("地址不存在");
        }
        if (!address.getUserId().equals(userId)) {
            throw new ServiceException("无权使用此地址");
        }

        List<OrderItemInsertForm> orderItemList = form.getOrderItemList();
        if (orderItemList == null || orderItemList.isEmpty()) {
            throw new ServiceException("订单项列表不能为空");
        }

        // 计算总金额并验证商品
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<BookOrderItem> orderItems = new ArrayList<>();
        
        for (OrderItemInsertForm itemForm : orderItemList) {
            // 检查商品是否存在
            BookProduct product = goodsService.selectByPrimaryKey(itemForm.getProductId());
            if (product == null) {
                throw new ServiceException("商品不存在: " + itemForm.getProductId());
            }
            if (product.getStatus() == null || product.getStatus() != 1) {
                throw new ServiceException("商品已下架: " + product.getTitle());
            }

            // 计算金额
            BigDecimal itemAmount = itemForm.getPrice().multiply(new BigDecimal(itemForm.getCount()));
            totalAmount = totalAmount.add(itemAmount);

            // 创建订单项
            BookOrderItem orderItem = new BookOrderItem();
            orderItem.setProductId(itemForm.getProductId());
            orderItem.setProductTitle(product.getTitle());
            // 清理图片URL中的换行符和空白字符
            String pic = product.getPic();
            if (pic != null) {
                pic = pic.trim().replaceAll("[\\r\\n]+", "");
            }
            orderItem.setProductPic(pic);
            orderItem.setPrice(itemForm.getPrice());
            orderItem.setCount(itemForm.getCount());
            orderItems.add(orderItem);
        }

        // 生成订单编号
        String orderNo = generateOrderNo();

        // 保存订单
        BookOrder order = new BookOrder();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setAddressId(addressId);
        order.setAmount(totalAmount);
        order.setStatus(0); // 0-待支付
        if (StringUtils.isNotBlank(form.getRemark())) {
            order.setRemark(form.getRemark());
        }

        int result = orderMapper.insert(order);
        if (result <= 0) {
            throw new ServiceException("生成订单失败");
        }

        Long orderId = order.getId();

        // 设置订单项订单ID并批量插入
        for (BookOrderItem orderItem : orderItems) {
            orderItem.setOrderId(orderId);
        }
        
        int itemResult = orderItemMapper.insertBatch(orderItems);
        if (itemResult <= 0) {
            throw new ServiceException("生成订单项失败");
        }

        return orderId;
    }

    @Override
    public Boolean update(BookOrder bookOrder) {
        return null;
    }

    @Override
    public Boolean updateStatus(Long orderId, Integer status) {
        return null;
    }

    /**
     * 更改订单状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(OrderUpdateStatusForm form) {
        if (!StpUtil.isLogin()) {
            throw new ServiceException("用户未登录");
        }
        Long userId = StpUtil.getLoginIdAsLong();

        BookOrder order = orderMapper.selectByPrimaryKey(form.getId());
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new ServiceException("无权操作此订单");
        }

        BookOrder updateOrder = new BookOrder();
        updateOrder.setId(form.getId());
        updateOrder.setStatus(form.getStatus());
        return orderMapper.update(updateOrder) > 0;
    }

    /**
     * 查询订单详情By订单Id
     */
    @Override
    public OrderDetailVo selectDetailById(Long orderId) {
        if (!StpUtil.isLogin()) {
            throw new ServiceException("用户未登录");
        }
        Long userId = StpUtil.getLoginIdAsLong();

        BookOrder order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new ServiceException("无权查看此订单");
        }

        OrderDetailVo orderDetailVo = toOrderDetailVo(order);
        List<OrderItemVo> orderItemVoList = orderItemMapper.selectVoListByOrderId(orderId);
        orderDetailVo.setOrderItemList(orderItemVoList);
        return orderDetailVo;
    }

    /**
     * 查询我的订单明细列表(有商品项)
     */
    @Override
    public List<OrderDetailVo> selectMyList(OrderQueryPageForm form) {
        if (!StpUtil.isLogin()) {
            throw new ServiceException("用户未登录");
        }
        Long userId = StpUtil.getLoginIdAsLong();

        BookOrder queryOrder = new BookOrder();
        queryOrder.setUserId(userId);
        if (form.getStatus() != null) {
            queryOrder.setStatus(form.getStatus());
        }

        List<OrderDetailVo> orderDetailVoList = orderMapper.selectVoMyList(queryOrder);
        // 为每个订单查询订单商品项
        for (OrderDetailVo orderDetailVo : orderDetailVoList) {
            List<OrderItemVo> orderItemVoList = orderItemMapper.selectVoListByOrderId(orderDetailVo.getId());
            orderDetailVo.setOrderItemList(orderItemVoList);
        }
        return orderDetailVoList;
    }

    private String generateOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8).toUpperCase();
        return "ORD" + dateStr + uuid;
    }

    private OrderDetailVo toOrderDetailVo(BookOrder order) {
        OrderDetailVo vo = new OrderDetailVo();
        vo.setId(order.getId());
        vo.setOrderNo(order.getOrderNo());
        vo.setUserId(order.getUserId());
        vo.setAddressId(order.getAddressId());
        vo.setAmount(order.getAmount());
        vo.setStatus(order.getStatus());
        vo.setRemark(order.getRemark());
        vo.setCreatedAt(order.getCreatedAt());
        vo.setUpdatedAt(order.getUpdatedAt());
        return vo;
    }
}
